package com.czy.seed.mvc.home.controller;

import com.alibaba.fastjson.JSONObject;
import com.czy.seed.mvc.home.entity.*;
import com.czy.seed.mvc.home.service.MenuService;
import com.czy.seed.mvc.home.service.MerchantService;
import com.czy.seed.mvc.home.service.OrderDetailService;
import com.czy.seed.mvc.home.service.OrderService;
import com.czy.seed.mvc.sys.entity.SysRole;
import com.czy.seed.mvc.sys.entity.SysUser;
import com.czy.seed.mvc.sys.entity.SysUserRole;
import com.czy.seed.mvc.sys.service.SysRoleService;
import com.czy.seed.mvc.sys.service.SysUserRoleService;
import com.czy.seed.mvc.sys.service.SysUserService;
import com.czy.seed.mvc.util.Cache;
import com.czy.seed.mvc.util.CacheManager;
import com.czy.seed.mvc.util.PrincipalUtil;
import com.czy.seed.mvc.util.Res;
import com.czy.seed.mybatis.base.QueryParams;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import javafx.beans.property.ReadOnlyIntegerPropertyBase;
import org.assertj.core.util.Compatibility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/home/order_detail")
public class OrderDetailController {
    public static Logger logger = LoggerFactory.getLogger(MerchantController.class);

    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderService orderService;

    @RequestMapping("/select")
    public Res select() {
        QueryParams queryParams = new QueryParams(OrderDetail.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("orderId", 0);
        criteria.andEqualTo("creation_by", PrincipalUtil.getLoginUser().getId());
        List<OrderDetail> orderDetail = orderDetailService.selectListByParams(queryParams);
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        pageInfo.put("orderDetail", orderDetail);
        return Res.ok(pageInfo);
    }


    @RequestMapping("/orderDetailSelect")
    public Res orderDetailSelect(HttpServletRequest request) {
        String lim = request.getParameter("lim");
        Commodity commodity = JSONObject.parseObject(lim, Commodity.class);
        QueryParams queryParams = new QueryParams(OrderDetail.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("commodityId", commodity.getId());
        List<OrderDetail> orderDetail = orderDetailService.selectListByParams(queryParams);
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        if (orderDetail.size() > 0) {
            pageInfo.put("orderDetail", orderDetail);
            return Res.ok(pageInfo);
        } else {
            return Res.ok();
        }
    }

    //向购物车添加商品
    @RequestMapping("/insertShopCart")
    public Res insertShopCart(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<>(16);
        try {
            String sell = request.getParameter("sell");
            if (Integer.parseInt(sell) == 0) {
                throw new Exception("该商家未入围，不能添加商品到购物车！");
            } else {
                String lim = request.getParameter("lim");
                String ids = request.getParameter("ids");
                if (ids == null || "".equals(ids)) {

                } else {
                    ids = ids.replace("undefined", "");
                }
                Commodity commodity = JSONObject.parseObject(lim, Commodity.class);
                if (commodity.getInstall() == 0 || commodity.getInstall() == 2) {
                    throw new Exception("该商品已下架，不能添加商品到购物车！");
                } else {
                    OrderDetail orderDetail = new OrderDetail();
                    orderDetail.setCommodityName(commodity.getCommodityName());
                    orderDetail.setCommodityMakPrc(commodity.getCommodityMakPrc().toString());
                    orderDetail.setCommodityTrcPrc(commodity.getCommodityTrcPrc().toString());
                    orderDetail.setCommodityTotal(commodity.getCommodityTrcPrc().toString());
                    orderDetail.setComparisonid(ids);
                    //默认添加进来购物车信息数量为1
                    orderDetail.setCommodityNum("1");
                    orderDetail.setCommoditySplPrc(commodity.getCommodityTrcPrc().toString());
                    orderDetail.setCommodityType(commodity.getCategory());
                    orderDetail.setCommodityId(commodity.getId());
                    orderDetail.setCreation_by(PrincipalUtil.getLoginUser().getId());
                    orderDetail.setMasterMap(commodity.getMasterMap());
                    orderDetail.setUnit(commodity.getUnit());
                    //没有生成订单信息
                    orderDetail.setCommodityGrade("0");
                    int result = orderDetailService.insert(orderDetail);
                    pageInfo.put("shopCart", result);
                }
            }
            logger.info("添加购物车成功");
        } catch (Exception e) {
            logger.error("添加购物车失败", e);
        }
        return Res.ok(pageInfo);
    }
    //删除购物车

    @RequestMapping("/deleteShop")
    public Res deleteShop(HttpServletRequest request) {
        String information = request.getParameter("information");
        try {
            OrderDetail orderDetail = JSONObject.parseObject(information, OrderDetail.class);
            QueryParams queryParams = new QueryParams(Estimate.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("orderId", orderDetail.getId());
            Long orderDetailId = orderDetail.getId();
            int orderDetailIdResult = orderDetailService.deleteByPrimaryKey(orderDetailId);
            if (orderDetailIdResult > 0) {
                Long ordersId = orderDetail.getOrderId();
                int ordersIdResult = orderService.deleteByPrimaryKey(ordersId);
                if (ordersIdResult > 0) {
                    logger.info("成功删除订单信息:{}", orderDetail.getCommodityName());
                }
            }
        } catch (Exception e) {
            logger.error("删除订单信息失败");
            return Res.error();
        }
        return Res.ok();
    }

    //购物车数据修改
    @RequestMapping("/updateShop")
    public Res updateShop(String results) {
        try {
            OrderDetail orderDetail = JSONObject.parseObject(results, OrderDetail.class);
            orderDetail.setCommodityNum(orderDetail.getCommodityNum());
            orderDetail.setCommoditySplPrc(orderDetail.getCommoditySplPrc());
            orderDetailService.updateByPrimaryKey(orderDetail);
            logger.info("成功修改订单信息:{}", orderDetail.getCommodityName());
        } catch (Exception e) {
            logger.error("修改订单信息失败");
        }
        return Res.ok();
    }

}
